#include "user.h"
#include "ui_user.h"

User::User(datebase *db,int flag,QString Name,QString Type,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::User)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    this->pt_mydb=db;
    userFlag=flag;
    ui->lineEdit_NewUserPass->setEchoMode(QLineEdit::PasswordEchoOnEdit);
    ui->lineEdit_NewUserPassSecond->setEchoMode(QLineEdit::PasswordEchoOnEdit);
    if(userFlag < 0)
    {
     ui->label_Title->setText("新增用户");
     ui->pushButton_NewUserAdd->setText("增加");
    }else{
     ui->label_Title->setText("用户修改");
     ui->lineEdit_NewUserName->setText(Name);
     int m=ui->comboBox_NewUserType->findText(Type);
     ui->comboBox_NewUserType->setCurrentIndex(m);
     ui->pushButton_NewUserAdd->setText("确认");
    }
}

User::~User()
{
    delete ui;
}

void User::on_pushButton_NewUserQuit_clicked()
{
    this->close();
}

void User::on_pushButton_NewUserAdd_clicked()
{

    if(ui->lineEdit_NewUserName->text().isEmpty())
    {
        QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("用户名为空"));
        return;
    }
    if(ui->lineEdit_NewUserPass->text().isEmpty() || ui->lineEdit_NewUserPassSecond->text().isEmpty())
    {
        QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("密码为空"));
        return ;
    }
    if(ui->lineEdit_NewUserPass->text() != ui->lineEdit_NewUserPassSecond->text())
    {
        QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("两次输入密码不同"));
        return ;
    }
    if(userFlag < 0)
    {
    QString str;
    bool res;
    str=this->pt_mydb->selectUserData(&this->pt_mydb->sqlite_db,ui->lineEdit_NewUserName->text());
    if(!str.isEmpty())
    {
        QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("用户名重复"));
        return ;

    }else{
        user_info userInfo;
        if(ui->comboBox_NewUserType->currentText()=="管理员")
        {
          userInfo.user_type="system";
        }else{
          userInfo.user_type="common";
        }
        userInfo.login=ui->lineEdit_NewUserName->text();
        userInfo.password=ui->lineEdit_NewUserPass->text();

        res=this->pt_mydb->insertUserData(&this->pt_mydb->sqlite_db,&userInfo);
        if(res)
        {
            QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("用户添加成功"));
            this->close() ;
        }else{
            QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("用户添加失败"));
            return ;
        }
    }
    }else{
        this->pt_mydb->updateUserData(&this->pt_mydb->sqlite_db,userFlag,ui->lineEdit_NewUserName->text(),ui->lineEdit_NewUserPass->text(),ui->comboBox_NewUserType->currentText());
        QMessageBox::information(this,QObject::trUtf8("提示"), QObject::trUtf8("用户修改成功"));
        this->close() ;
    }
}
